package com.example.common.config;

import java.util.List;

import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;

import com.fasterxml.jackson.databind.ObjectMapper;

@Configuration
public class HttpMessageConverterConfig {

	@Bean
	public HttpMessageConverters messageConverters(ObjectMapper objectMapper) {
		return new HttpMessageConverters() {
			@Override
			protected List<HttpMessageConverter<?>> postProcessConverters(List<HttpMessageConverter<?>> converters) {
				var index = 0;

				for (var i = 0; i < converters.size(); i++) {
					var converter = converters.get(i);

					if (converter instanceof MappingJackson2HttpMessageConverter) {
						index = i;
					}
				}

				converters.remove(index);

				var jsonConverter = new MappingJackson2HttpMessageConverter(objectMapper);

				converters.add(jsonConverter);

				return converters;
			}
		};
	}
}
